package com.yx.frame.builder.code;

import java.util.List;

import org.jdom.Element;

import com.yx.frame.builder.validate.Validator;
import com.yx.frame.builder.xml.JavaMethodContentXml;
import com.yx.frame.builder.xml.MethodMencacheXml;
import com.yx.frame.builder.xml.MethodParmXml;
import com.yx.frame.builder.xml.MethodXml;



public class JavaMethodBuilder extends MethodBuilder {

	public JavaMethodBuilder(String className,String shortClassName, MethodXml method) throws Exception {
		super(className,shortClassName, method);	
	}

	public StringBuffer getJavaCode() throws Exception {
		String parmSre = "user,";
		List<MethodParmXml> methodParms=getMethod().getMethodParms();
		for (int i = 0; i < methodParms.size(); i++) {
			MethodParmXml methodParmXml = methodParms.get(i);
			parmSre = parmSre + methodParmXml.getName() + ",";
		}
		if (parmSre.endsWith(",")) {
			parmSre = parmSre.substring(0, parmSre.length() - 1);
		}
		StringBuffer code = new StringBuffer();
		code.append("\r\n");
		code.append("	/////////////////////////////////////////////////////////////////////\r\n");
		code.append("	//编号：" + this.getMethod().getId() + "\r\n");
		code.append("	//说明：" + this.getMethod().getComment() + "\r\n");
		code.append("	//作者：" + this.getMethod().getAuthor() + "\r\n");
		code.append("	//日期：" + this.getMethod().getDate() + "\r\n");
		code.append("	/////////////////////////////////////////////////////////////////////\r\n");
		code.append("\r\n");

		code.append("	//外部调用方法，用于客户端远程调用服务\r\n");
		code.append("	public static ServiceResult " + this.getMethod().getName()	+ "(User user, JSONObject obj)throws Exception {\r\n");
		//List<MethodParmXml> methodParms=getMethod().getMethodParms();
		for (int i = 0; i < methodParms.size(); i++) {
			MethodParmXml methodParmXml = methodParms.get(i);
			if (methodParmXml.isMutilistType()) {
				code.append("		JSONArray " + methodParmXml.getName()+ "=obj.getJSONArray(\"" + methodParmXml.getName()	+ "\");\r\n");
			} else {
				code.append("		String " + methodParmXml.getName()+ "=obj.getString(\"" + methodParmXml.getName()+ "\");\r\n");
			}
			Validator[] validators = methodParmXml.getValidators();
			if(methodParmXml.isMutilistType()){
				if(validators.length>0){
					code.append("		if("+methodParmXml.getName()+"==null)return new ServiceError(\""+ methodParmXml.getComment() +"不能为空\");\r\n");
					code.append("		for(int i=0,n="+methodParmXml.getName()+".length();i<n;i++){\r\n");
					for (int vIdx = 0; vIdx < validators.length; vIdx++) {
						Validator validator = validators[vIdx];
						code.append("			if(!" + validator.getStaticMethodName() + "("+ methodParmXml.getName() + ".getString(i))) return new ServiceError(\""+ methodParmXml.getComment() +"要求填写"
								+ validator.getComment() + "\");\r\n");
					}
				code.append("		}\r\n");
				}
			}else{
				for (int vIdx = 0; vIdx < validators.length; vIdx++) {
					Validator validator = validators[vIdx];
					code.append("		if(!" + validator.getStaticMethodName() + "("+ methodParmXml.getName() + ")) return new ServiceError(\""+ methodParmXml.getComment() +"要求填写"
						+ validator.getComment() + "\");\r\n");
				}
			}
		}
		MethodMencacheXml methodMencacheXml=this.getMethod().getMethodMencacheXml();
		if("true".equals(methodMencacheXml.getCached())||"true".equals(methodMencacheXml.getStaticfile())){
			code.append("		String memcachedKey="+methodMencacheXml.getMencacheKey(getMethod().getId(),"false")+";\r\n");
		}
		if("true".equals(methodMencacheXml.getCached())){
			//code.append("		String memcachedKey="+methodMencacheXml.getMencacheKey(getMethod().getId(),"false")+";\r\n");
			code.append("		ServiceResult memcachedJSONObject=getServiceMemStorage(memcachedKey);\r\n");
			code.append("		if(memcachedJSONObject!=null)return memcachedJSONObject;\r\n");
		}
		if("true".equals(methodMencacheXml.getStaticfile())){
			code.append("		ServiceResult staticSaveedJSONObject=getServiceFileStorage(memcachedKey,"+methodMencacheXml.getStaticfileDays()+");\r\n");
			code.append("		if(staticSaveedJSONObject!=null)return staticSaveedJSONObject;\r\n");
		}
		JavaMethodContentXml javaMethodContentXml=(JavaMethodContentXml)getMethod().getMethodContentXml();
		code.append("		ServiceResult result= " + javaMethodContentXml.getClassname() + "."	+ javaMethodContentXml.getStaticMethodName()+ "(" + parmSre + ");\r\n");
		code.append("		result.setServiceMessage(\"执行成功\");\r\n");
		if("true".equals(methodMencacheXml.getCached())){
			code.append("		setServiceMemStorage(memcachedKey,result,"+methodMencacheXml.getCatcheTimeout()+");\r\n");
		}
		if("true".equals(this.getMethod().getRemoveMemcachedUserLicense())){
			code.append("		user.removeMemStoragedUser();\r\n");
		}
		code.append("		return result;\r\n");
		code.append("	}\r\n");
		return code;
	}
	public StringBuffer[] getJsWebCode(String jsControlName) throws Exception{
		StringBuffer code = new StringBuffer();
		
		String jsParmsStr = "";
		String jsonParm = "";
		String parmInputDiscription="";
		List<MethodParmXml> methodParms=getMethod().getMethodParms();
		for (int i = 0; i < methodParms.size(); i++) {
			MethodParmXml methodParmXml = methodParms.get(i);
			jsParmsStr = jsParmsStr + methodParmXml.getName() + ",";
			if (methodParmXml.isMutilistType()) {
				jsonParm = jsonParm + methodParmXml.getName()
						+ ":" + methodParmXml.getName() + ",";
			} else {
				jsonParm = jsonParm + methodParmXml.getName() + ":"
						+ methodParmXml.getName() + ",";
			}
			if(methodParmXml.isMutilistType()){
				parmInputDiscription=parmInputDiscription+(i+1)+"、"+methodParmXml.getName()+"："+methodParmXml.getComment()+"&nbsp;-"+methodParmXml.getType()+"数组（"+methodParmXml.getValidator()+"）<br>";
			}else{
				parmInputDiscription=parmInputDiscription+(i+1)+"、"+methodParmXml.getName()+"："+methodParmXml.getComment()+"&nbsp;-"+methodParmXml.getType()+"（"+methodParmXml.getValidator()+"）<br>";
			}
		}
		String sampleParmStr=jsParmsStr;
		sampleParmStr=splitParmsHtml(sampleParmStr);
		jsParmsStr = jsParmsStr + "callbackFunction,";
		if (jsParmsStr.endsWith(","))
			jsParmsStr = jsParmsStr.substring(0, jsParmsStr.length() - 1);
		if (jsonParm.endsWith(","))
			jsonParm = jsonParm.substring(0, jsonParm.length() - 1);
		jsonParm = "{" + jsonParm + "}";

		//code.append("\r\n");
		StringBuffer sampleString=new StringBuffer();
		sampleString.append("	"+jsControlName+"." +this.getMethod().getName()+"_"+this.getMethod().getId() + "("+sampleParmStr+"function(isOK,message,jsonData){ <br>  \r\n");
		sampleString.append("	    &nbsp;&nbsp;if(isOK){//服务调用成功,从jsonData中取出返回数据<br>\r\n");
		sampleString.append("	    &nbsp;&nbsp;}else{//服务调用失败，返回错误信息<br>\r\n");
		sampleString.append("	        &nbsp;&nbsp;&nbsp;&nbsp;var errorMessage=message;<br>\r\n");
		sampleString.append("	    &nbsp;&nbsp;}<br>\r\n");
		sampleString.append("	});\r\n");		
		StringBuffer html=JsFileWriter.htmlStr(this.getMethod().getIsMobilApp(),""+this.getMethod().getId(),
				this.getMethod().getName()+"_"+this.getMethod().getId() + "("	+ splitParmsHtml(jsParmsStr) + ")", this.getMethod().getComment(), this.getMethod().getAuthor(), this.getMethod().getDate(), parmInputDiscription, "JSON对象，具体格式请alert出来", sampleString.toString());
		
		//code.append("\r\n");
		code.append("	this."+ this.getMethod().getName()+"_" +this.getMethod().getId()+ "=function(" + jsParmsStr
				+ "){");
		code.append("var data = " + jsonParm + ";");
		code.append("this.jsonPost("+this.getMethod().getId()+","+this.getMethod().getAsyncService()+",data,function(jsonData,callback){callback(jsonData.IsOK, jsonData.Message,jsonData);},callbackFunction);");
		code.append("};\r\n");
		return new StringBuffer[]{code,html};
	}			
}
